package syn.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import syn.entity.Student;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018\3\4 0004.
 */
public class StudentDaoImpl implements StudentDao{

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int addStudent(Student student) {
        String sql="insert into t_student VALUES (null,?,?,500)";
        Object [] objects={student.getName(),student.getAge()};
        return jdbcTemplate.update(sql,objects);
    }

    public int updateStudent(Student student) {
        String sql="update   t_student set name=?, age=? where id=?";
        Object [] objects={student.getName(),student.getAge(),student.getId()};
        return jdbcTemplate.update(sql,objects);
    }

    public int deleteStudent(int id) {
        String sql="delete from t_student where id=?";
        Object [] objects={id};
        return jdbcTemplate.update(sql,objects);
    }

    public List queryStudents() {
        String sql="select * from t_student";
        final List list=new ArrayList();
        jdbcTemplate.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                Student student=new Student();
                student.setId(rs.getInt("id"));
                student.setAge(rs.getInt("age"));
                student.setName(rs.getString("name"));
                list.add(student);
            }
        });
        return list;
    }

    public int inMoney(int id, Double money) {
        String sql="update   t_student set money=money+? where id=?";
        Object [] objects={money,id};
        return jdbcTemplate.update(sql,objects);
    }

    public int outMoney(int id, Double money) {
        String sql="update   t_student set money=money-? where id=?";
        Object [] objects={money,id};
        return jdbcTemplate.update(sql,objects);
    }
}
